package com.green.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Clob;
import java.sql.SQLException;

public abstract class StreamUtils {
	public static final int DEFAULT_BUFFER_SIZE = 2048;
	public static final int CLOBPOS = 1;

	/**
	 * 把object转换成输出流 目前支持2种
	 * 
	 * @param obj
	 * @return
	 */
	public static InputStream asInputStream(Object obj) {
		if (obj == null) {
			return null;
		}
		final boolean isStringType = obj instanceof String;
		if (isStringType) {
			final String str = (String) obj;
			try {
				return new ByteArrayInputStream(str.getBytes("iso-8859-1"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		final boolean isClobType = obj instanceof Clob;
		if (isClobType) {
			final Clob c = (Clob) obj;
			try {
				return c.getAsciiStream();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		throw new RuntimeException("目前只支持String类型和Clob类型");
	}

	public static void copy(InputStream input, OutputStream output) throws IOException {
		copy(input, output, 2048);
	}

	public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
		byte[] buf = new byte[bufferSize];
		int bytesRead = input.read(buf);
		while (bytesRead != -1) {
			output.write(buf, 0, bytesRead);
			bytesRead = input.read(buf);
		}
		output.flush();
	}

	public static void copyThenClose(InputStream input, OutputStream output) throws IOException {
		copy(input, output);
		input.close();
		output.close();
	}

	public static byte[] getBytes(InputStream input) throws IOException {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		copy(input, result);
		result.close();
		return result.toByteArray();
	}
}